package com.shaw.installAPKapi.controller;


import com.shaw.installAPKapi.repository.UpdateInfo;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;

@RestController
public class UpdateApi {
    @GetMapping("/version")
    public UpdateInfo getUpdate(){
        UpdateInfo updateInfo = new UpdateInfo();
        updateInfo.setVersion("2.0.0");
        updateInfo.setSuccess(true);
        updateInfo.setUrl("http://192.168.0.103/download/app-debug.apk");
        return updateInfo;
    }


    private static final String FILE_STORAGE_PATH = "D:\\codeLib\\test_project\\api-Service\\installAPKapi\\src\\main\\resources\\repository\\";

    @GetMapping("/download/{fileName}")
    public ResponseEntity<FileSystemResource> downloadFile(@PathVariable String fileName) {
        // 构建文件路径
        String filePath = FILE_STORAGE_PATH + fileName;
        File file = new File(filePath);

        // 检查文件是否存在
        if (!file.exists()) {
            return ResponseEntity.notFound().build();
        }

        // 创建 FileSystemResource
        FileSystemResource fileSystemResource = new FileSystemResource(file);

        // 设置响应头
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"")
                .body(fileSystemResource);
    }
}
